var express = require('express')
var connection = require('../db/db_utill');

var router = express.Router()

//获取用户信息
router.get('/user_info', function (req, res) {
  //获取url发送用户点击话题的id
  const id = req.query.id

  connection.query(`SELECT * FROM 
  user_info
  WHERE user_id = ?`, [id], function (error, results, fields) {
    if (error) {
      throw error;
    } else if (results.length) {
      const string = JSON.stringify(results);
      const jsons = JSON.parse(string)[0];
      res.json(
        jsons
      )
    }
  });
})

// 修改用户信息
router.put('/user_info', function (req, res) {

  //获取put请求前端传递的数据
  const body = req.body
  const userInfo = [body.username, body.header_pic, body.self_sign, body.address, body.school, body.user_id]
  connection.query(`UPDATE user_info SET 
  username = ?,
  header_pic = ?,
  self_sign = ?,
  address = ?,
  school = ?
  WHERE user_id = ?`, userInfo, function (error, results, fields) {
    if (error) {
      throw error;
    } else {
      res.json(
        {
          message: '修改成功！',
          status: 200
        }
      )
    }
  });
})

//获取用户发布的话题
router.post('/self_topic', function (req, res) {
  //获取url发送用户点击话题的id
  const body = req.body

  connection.query('SELECT * FROM `topic_info` where user_id=? and topic_state=0', [body.id], function (error, results, fields) {
    if (error) {
      throw error;
    } else if (results.length) {
      const string = JSON.stringify(results);
      const topic_info = JSON.parse(string);
      res.status(200).json({
        status: 200,
        //话题数据
        topic_info

      })
    } else {
      res.json({
        message: '获取数据失败！'
      })
    }
  });
})

//获取用户审核的话题
router.post('/chect_topic', function (req, res) {
  //获取url发送用户点击话题的id
  const body = req.body

  connection.query('SELECT * FROM `topic_info` where user_id=? and topic_state=1', [body.id], function (error, results, fields) {
    if (error) {
      throw error;
    } else if (results.length) {
      const string = JSON.stringify(results);
      const topic_info = JSON.parse(string);
      res.status(200).json({
        status: 200,
        //话题数据
        topic_info

      })
    } else {
      res.json({
        message: '获取数据失败！'
      })
    }
  });
})

// 取出收藏的话题
router.post('/favorite_topic', function (req, res) {

  const body = req.body

  connection.query(`select * from
  topic_info t1,
  favorite_topic t2 
  where t2.user_id = ?
  and t2.topic_id= t1.topic_id`, [body.id], function (error, results, fields) {
    if (error) {
      throw error;
    } else {
      const string = JSON.stringify(results);
      const topic_info = JSON.parse(string);
      res.status(200).json({
        status: 200,
        //话题数据
        topic_info

      })
    }
  });
})

module.exports = router;
